package com.pri.chat.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.MemberBean;
import com.netease.nim.uikit.net.entity.PayResultBean;
import com.netease.nim.uikit.net.entity.RechargeBondBean;
import com.netease.nim.uikit.net.entity.UserBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.adapter.RechargeVIPAdapter;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.base.TcWebActivity;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.model.RechargePayModel;
import com.pri.chat.model.UserModel;
import com.pri.chat.pay.PayListenerUtils;
import com.pri.chat.pay.PayResultListener;
import com.pri.chat.pay.PayUtils;
import com.pri.chat.utils.Des3Util;
import com.vondear.rxtool.view.RxToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/24
 */
public class VipCenterActivity extends BaseActivity implements PayResultListener {
    @BindView(R.id.rec_recharge)
    RecyclerView recRecharge;
    @BindView(R.id.svipInfoRelation)
    RelativeLayout svipInfoRelation;
    @BindView(R.id.svipImage)
    ImageView svipImage;



    @BindView(R.id.vipRelation)
    RelativeLayout vipRelation;
    @BindView(R.id.vipTv)
    TextView vipTv;

    @BindView(R.id.vipImage)
    ImageView vipImage;

    @BindView(R.id.svipRelation)
    RelativeLayout svipRelation;
    @BindView(R.id.svipTv)
    TextView svipTv;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.svipmonth)
    TextView svipmonth;
    @BindView(R.id.svipPrice)
    TextView svipPrice;

    @BindView(R.id.ygmLinear)
    View ygmLinear;
    @BindView(R.id.yqmTv)
    TextView yqmTv;
    @BindView(R.id.yqmYqbtn)
    TextView yqmYqbtn;

    @BindView(R.id.wgmLinear)
    View wgmLinear;
    @BindView(R.id.yqmEdit)
    EditText yqmEdit;
    @BindView(R.id.yqmBtnSubmit)
    TextView yqmBtnSubmit;
    @BindView(R.id.cjhyInfo)
    ImageView cjhyInfo;



    private int selectVipType = 1; //0--vip;2--svip

    @Override
    protected int getLayoutId() {
        return R.layout.activity_vip_center_layout;
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            setUserInfo();
        }
    };

    @Override
    protected void initView() {
        setTitle("会员中心");
        PayListenerUtils.getInstance(this).addListener(this);
        IntentFilter intentFilter = new IntentFilter("PaySuccess");
        registerReceiver(broadcastReceiver, intentFilter);
        initRv();
        getMemberInfoByMemberId();
    }


    private List<RechargeBondBean> mlist;
    private RechargeVIPAdapter mAdapter;
    private int mPosition;

    private void initRv() {
        yqmBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(yqmEdit.getText().toString().isEmpty()){
                    RxToast.normal("请填写邀请码！");
                    return;
                }
                httpSet();
            }
        });

        yqmYqbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(yqmTv.getText().toString());
                RxToast.normal("复制成功，请发给想邀请的人！");
            }
        });

        cjhyInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(mContext, TcWebActivity.class);
                intent.putExtra("title","超级会员规则");
                intent.putExtra("url", HttpMethods.BASE_URL+"p/front_editorHtmlShow.html?code=superVipInfoCode");
                startActivity(intent);
            }
        });

        mlist = new ArrayList<>();
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this,3);
        recRecharge.setLayoutManager(linearLayoutManager);
        recRecharge.setNestedScrollingEnabled(false);
        mAdapter = new RechargeVIPAdapter(R.layout.item_recharge_vip, mlist);
        recRecharge.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            mPosition = position;
            for (int i = 0; i < mlist.size(); i++) {
                if (i == position) {
                    mlist.get(position).setCheck(true);
                } else {
                    mlist.get(i).setCheck(false);
                }
            }
            mAdapter.notifyDataSetChanged();
        });
    }

    private void getMemberInfoByMemberId() {
        SubscriberOnNextListener<BaseBean<MemberBean>> onNextListener = baseBean -> {
            SharedHelper.saveKeyValueForString(mContext,"SVIP",baseBean.getData().getIsSupperVip());
            SharedHelper.saveKeyValueForString(mContext,"SVIPCODE",baseBean.getData().getSuperVipCode());
            yqmTv.setText(SharedHelper.readValueByKeyForString(mContext,"SVIPCODE"));
        };
        Map<String,Object> reqObj = new HashMap<>();
        reqObj.put("memberId", SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(reqObj));
        HttpMethods.getInstance().getMemberInfoByMemberId(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    /**
     * 绑定邀请码
     */
    private void httpSet() {
        SubscriberOnNextListener<BaseBean<String>> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMsg());
            SharedHelper.saveKeyValueForString(mContext,"sjId",baseBean.getData());
            wgmLinear.setVisibility(View.GONE);
            ygmLinear.setVisibility(View.VISIBLE);
//            yqmTv.setText(SharedHelper.readNimId(mContext));

        };
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",SharedHelper.readId(this));
        params.put("code",yqmEdit.getText().toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().bindCode(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    private void httpBuy(int type) {
        String id = mlist.get(mPosition).getId();
        SubscriberOnNextListener<BaseBean<PayResultBean>> onNextListener = baseBean -> {
            if (type == 0) {
                PayUtils.getInstance(this).alipay(PayUtils.PAY_TYPE_ALI, baseBean.getData().getAlipay());
            } else {
                PayUtils.getInstance(this).wxpay(PayUtils.PAY_TYPE_WX, baseBean.getData().getWxpay());
            }
        };
        RechargePayModel rechargePayModel = new RechargePayModel();//登录上传参数
        rechargePayModel.setMemberId(SharedHelper.readId(this));
        rechargePayModel.setObjId(id);
        rechargePayModel.setPayType(type);
        rechargePayModel.setType(selectVipType);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(rechargePayModel));
        HttpMethods.getInstance().createOrder(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(broadcastReceiver);
        PayListenerUtils.getInstance(this).removeListener(this);
    }

    @Override
    protected void initData() {
        SubscriberOnNextListener<BaseBean<List<RechargeBondBean>>> onNextListener = baseBean -> {
            for(int i=0;i<baseBean.getData().size();i++){
                if(baseBean.getData().get(i).getName().contains("SVIP")){
                    svipmonth.setText(baseBean.getData().get(i).getVipMonth()+"个月");
                    svipPrice.setText("¥"+baseBean.getData().get(i).getMoney()+"元");
                    baseBean.getData().remove(i);
                    break;
                }
            }
            mlist.addAll(baseBean.getData());
            mlist.get(0).setCheck(true);
            mAdapter.notifyDataSetChanged();
        };

        HttpMethods.getInstance().listChargeVip(new ProgressSubscriber<>(onNextListener, this, true));
    }

    private void setUserInfo() {
        SubscriberOnNextListener<BaseBean<UserBean>> onNextListener = baseBean -> {
            UserBean userBean = baseBean.getData();
            if (userBean.getMemberInfo().getMemberLevel().equals("否")) {
//               tvPrice.setText("您还不是VIP");
//               rlBg.setBackgroundResource(R.drawable.btn_z_gray_10_shape);
            } else {
//                tvPrice.setText("VIP");
//                rlBg.setBackgroundResource(R.drawable.btn_orange_gradient_z_shape);
            }
        };
        UserModel userModel = new UserModel();
        userModel.setMemberId(SharedHelper.readId(this));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().getMemberCenterInfo(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }


    @Override
    public void onPaySuccess() {
        setUserInfo();
        getMemberInfoByMemberId();
    }

    @Override
    public void onPayError() {

    }

    @Override
    public void onPayCancel() {

    }

    @OnClick({R.id.tv_pay,R.id.vipRelation,R.id.svipRelation})
    public void onViewClicked(View v) {
        if(v.getId() == R.id.tv_pay){
            initShareDialog();
        }else if(v.getId() == R.id.vipRelation){
            selectVipType = 1;
            vipRelation.setBackgroundResource(R.drawable.btn_orange_noconer_line_shape);
            vipTv.setTextColor(mContext.getResources().getColor(R.color.orange));
            svipRelation.setBackgroundResource(R.drawable.btn_gray_noconer_line_shape);
            svipTv.setTextColor(mContext.getResources().getColor(R.color.color_333333));
            recRecharge.setVisibility(View.VISIBLE);
            vipImage.setVisibility(View.VISIBLE);
            svipInfoRelation.setVisibility(View.GONE);
            svipImage.setVisibility(View.GONE);
            wgmLinear.setVisibility(View.GONE);
        }else if(v.getId() == R.id.svipRelation){
            selectVipType = 2;
            vipRelation.setBackgroundResource(R.drawable.btn_gray_noconer_line_shape);
            vipTv.setTextColor(mContext.getResources().getColor(R.color.color_333333));
            svipRelation.setBackgroundResource(R.drawable.btn_orange_noconer_line_shape);
            svipTv.setTextColor(mContext.getResources().getColor(R.color.orange));
            recRecharge.setVisibility(View.GONE);
            vipImage.setVisibility(View.GONE);
            svipInfoRelation.setVisibility(View.VISIBLE);
            svipImage.setVisibility(View.VISIBLE);
            if(SharedHelper.readValueByKeyForString(mContext,"SVIP").equals("是")){
                wgmLinear.setVisibility(View.GONE);
                ygmLinear.setVisibility(View.VISIBLE);
                yqmTv.setText(SharedHelper.readValueByKeyForString(mContext,"SVIPCODE"));
            }else{
                if(StringUtil.isEmpty(SharedHelper.readValueByKeyForString(this,"SVIPCODE"))){
                    wgmLinear.setVisibility(View.VISIBLE);
                    ygmLinear.setVisibility(View.GONE);
                }else{
                    wgmLinear.setVisibility(View.GONE);
                    ygmLinear.setVisibility(View.VISIBLE);
                    yqmTv.setText(SharedHelper.readValueByKeyForString(mContext,"SVIPCODE"));
                }
            }
        }

    }


    private Dialog mShareDialog;
    private void initShareDialog() {
        mShareDialog = DialogUtil.getInstance().showPayDialog(this);
        DialogUtil.getInstance().setOnPayClickListener(new DialogUtil.OnPayClickListener() {

               @Override
               public void onYuE(View v) {
               }

               @Override
               public void onAliPay(View v) {
                   httpBuy(0);
                   mShareDialog.dismiss();
               }

               @Override
               public void onWeiXinPay(View v) {
                   httpBuy(1);
                   mShareDialog.dismiss();
               }
            }
        );
        mShareDialog.show();
    }
}
